#!/bin/bash
# springboot应用自动根据git源码更新编译，并执行

prefix="notax-public-api"
log_file="/opt/adm/logs/${prefix}/${prefix}.log"
src_dir="/opt/adm/src/${prefix}"
jar_dir="/opt/adm/${prefix}"

function build {
    echo "开始更新源码并打包复制替换"
    cd ${src_dir}
    branch=$(git branch |awk '{print $2}')
    git pull origin ${branch}
    echo "更新完代码开始重新打包"
    mvn clean && mvn package -DskipTests=true
    if [[ "$?" != "0" ]]; then
        echo "编译出错，退出！"
        exit 1
    fi
    jarfile=$(ls target/*.jar)
    /bin/cp ${jarfile} ${jar_dir}
    cd ${jar_dir}
    echo "打包和复制完成"
}

function start {
    profile="$1"
    echo "启动环境profile=${profile}"
    jarfile=$(ls ${prefix}*.jar)
    echo "jarfile=${jarfile}"
    stop $jarfile

    if [[ -f "temp.log" ]]; then
        echo "" > temp.log
    fi

    ls application.yml &>/dev/null
    if [[ "$?" == "0" ]]; then
        echo "当前目录找到配置文件application.yml，执行外部配置"
        echo "nohup java -jar -Djava.security.egd=file:/dev/../dev/urandom -Dspring.profiles.active=${profile} ${jarfile} --spring.config.location=file:./application.yml >temp.log 2>&1 &"
        nohup java -jar -Djava.security.egd=file:/dev/../dev/urandom -Dspring.profiles.active=${profile} ${jarfile} --spring.config.location=file:./application.yml >temp.log 2>&1 &
    else
        echo "当前目录未找到配置文件application.yml，执行内部配置"
        echo "nohup java -jar -Djava.security.egd=file:/dev/../dev/urandom -Dspring.profiles.active=${profile} ${jarfile} >temp.log 2>&1 &"
        nohup java -jar -Djava.security.egd=file:/dev/../dev/urandom -Dspring.profiles.active=${profile} ${jarfile} >temp.log 2>&1 &
    fi
    echo "启动应用中，请查看日志文件: ${log_file}"
}

function stop {
    jarfile="$1"
    ps aux | grep " ${jarfile}" | grep -v grep > /dev/null
    if [[ "$?" == "0" ]]; then
        echo "发现应用还在跑，我先停了它"
        pid=$(ps aux | grep " ${jarfile}" | grep -v grep |awk '{print $2}')
        if [[ "$pid" != "" ]]; then
            echo "kill -9 $pid"
            kill -9 $pid
            echo "停止应用成功..."
        else
            echo "奇怪，我没有找到应用pid，停止应用失败"
        fi
    fi
}

if [[ "$1" == "start" ]]; then
    if [[ "$#" < 2 ]]; then
        echo "请输入正确参数：./run.sh start {profile}"
        exit 1
    fi
    profile="$2"
    if [[ "$profile" != "dev" && "$profile" != "test" && "$profile" != "prod" ]]; then
        echo "参数错误，请输入正确的profile参数，使用方法："
        echo "./run.sh start {profile} ==> 启动应用，{profile}取值：dev|test|prod"
        exit 1
    fi
    build
    start "${profile}"
elif [[ "$1" == "stop" ]]; then
    jarfile=$(ls ${prefix}*.jar)
    stop $jarfile
else
    echo "参数错误，使用方法："
    echo "./run.sh start {profile}     ==> 启动应用，{profile}取值：dev|test|prod"
    echo "./run.sh stop                ==> 停止应用"
    exit 1
fi

